package org.kobu;

import java.io.File;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

public class FilesIterator implements Iterator<FileData> {

    private final Stack<FileData> stack = new Stack<FileData>();

    private FileData nextItem;

    public FilesIterator(final File root) {
        stack.push(new FileData(root, ""));
        nextItem = prepareNextItem();
    }

    @Override
    public boolean hasNext() {
        return nextItem != null;
    }

    @Override
    public FileData next() {
        if (nextItem != null) {
            final FileData result = nextItem;
            nextItem = prepareNextItem();
            return result;
        } else {
            throw new NoSuchElementException();
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    private FileData prepareNextItem() {
        if (!stack.isEmpty()) {
            final FileData next = stack.pop();
            if (next.isDirectory()) {
                final File[] files = next.getFile().listFiles();
                if (files != null) {
                    for (final File file : files) {
                        stack.push(new FileData(file, next.getRelativePath() + File.separatorChar + file.getName()));
                    }
                } else {
                    System.err.println("I/O error while getting the content of the '" + next.getFile() + "' folder.");
                }
            }
            return next;
        } else {
            return null;
        }
    }
}
